<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Notification;
use App\Notifications\ForgetPassword as forget;
class ForgetPassword extends Controller
{
    public function writeEmail(){
    	return view('forgetpassword.writeemail');
	}
	public function check(Request $request){
    	$this->validate ($request,[
    		'email'=>'required|email'
		]);
		$email=$request->input('email');
		$user=User::where('email',$email)->first();
		if($user){
			Notification::send ($user,new forget($email,$user->email_token));
			session()->flash ('success','密码重置邮件已经发送到您的邮箱，请登录邮箱重置密码');
			return view('forgetpassword.send');
		}else{
			session()->flash ('danger','该邮箱不存在！');
			return redirect ()->back();
		}
	}
	public function resetView($email,$token){
    	return view('forgetpassword.reset',compact('email','token'));
	}
	public function reset(Request $request){
    	$this->validate ($request,[
    		'email_token'=>'required',
    		'email'=>'required|email',
			'password'=>'required|min:5|confirmed',
			'password_confirmation'=>'required|min:5'
    	]);
		$user=User::where('email',$request->input('email'))->first();
		if($user&&$user->email_token==$request->input('email_token')){
			$user->password=bcrypt($request->input('password'));
			$user->save();
			session()->flash('success','密码修改成功！');
			return redirect ()->route ('login');
		}else{
			session()->flash('danger','该账户不存在！');
			return redirect ()->route('login');
		}
	}
}
